package com.ruoyi.system.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.core.domain.entity.SysOrder;
import com.ruoyi.system.domain.SysUserOrderProperty;
import com.ruoyi.system.mapper.SysPropertyMapper;
import com.ruoyi.system.mapper.SysUserOrderPropertyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.SysOrderMapper;
import com.ruoyi.system.service.ISysOrderService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单详情Service业务层处理
 *
 * @author ssd
 * @date 2024-04-18
 */
@Service
public class SysOrderServiceImpl implements ISysOrderService
{
    @Autowired
    private SysOrderMapper sysOrderMapper;
    @Autowired
    private SysPropertyMapper sysPropertyMapper;
    @Autowired
    private SysUserOrderPropertyMapper sysUserOrderPropertyMapper;
    private static final Logger logger = LoggerFactory.getLogger(SysOrderServiceImpl.class);

    /**
     * 查询订单详情
     *
     * @param orderId 订单详情主键
     * @return 订单详情
     */
    @Override
    public SysOrder selectSysOrderByOrderId(Long orderId)
    {
        return sysOrderMapper.selectSysOrderByOrderId(orderId);
    }

    /**
     * 查询订单详情列表
     *
     * @param sysOrder 订单详情
     * @return 订单详情
     */
    @Override
    public List<SysOrder> selectSysOrderList(SysOrder sysOrder)
    {
        return sysOrderMapper.selectSysOrderList(sysOrder);
    }

    /**
     * 新增订单详情
     *
     * @param sysOrder 订单详情
     * @return 结果
     */
    @Override
    @Transactional
    public int insertSysOrder(SysOrder sysOrder) {

        if (sysOrder.getStartTime() == null || sysOrder.getDuration() == null) {
            throw new IllegalStateException("startTime or duration is null");
        }

        // 将租赁时长转换为月数
        int rentalMonths;
        try {
            rentalMonths = Integer.parseInt(sysOrder.getDuration());
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Invalid duration format. Expected an integer representing the number of months.", e);
        }

        // 将 startTime 转换为 LocalDate
        LocalDate startDate = convertToLocalDate(sysOrder.getStartTime());

        // 计算结束日期
        LocalDate endDate = startDate.plusMonths(rentalMonths);
        sysOrder.setEndTime(convertToDate(endDate));

        // 检查 SysProperty 是否包含必要字段
//        if (sysOrder.getProperty() == null || sysOrder.getProperty().getPrice() == null || sysOrder.getProperty().getDepositRule() == null) {
//            String errorMessage = "SysOrder ID 为 " + sysOrder.getOrderId() + " 的 SysProperty 缺少必要字段";
//            System.out.println(errorMessage);
//            throw new RuntimeException(); // 抛出自定义异常或替换为其他适合的异常类型
//        }

        BigDecimal totalPrice = sysOrder.getProperty().getPrice().multiply(BigDecimal.valueOf(Integer.parseInt(sysOrder.getDuration())));

        Integer depositRule = sysOrder.getProperty().getDepositRule();

        switch (depositRule) {
            case 0: // 无押金
                break;
            case 1: // 押一付一
                totalPrice = totalPrice.multiply(BigDecimal.valueOf(2)); // 总价 = 1个月租金 + 1个月押金
                break;
            case 3: // 押一付三
                totalPrice = totalPrice.multiply(BigDecimal.valueOf(4)); // 总价 = 3个月租金 + 1个月押金
                break;
            default:
                throw new IllegalArgumentException("Unsupported deposit rule: " + depositRule);
        }
        sysOrder.setTotalPrice(totalPrice);
        //修改房源状态为已租
        sysPropertyMapper.updateSysPropertyStatus(1);
        return sysOrderMapper.insertSysOrder(sysOrder);
    }
    private LocalDate convertToLocalDate(Date date) {
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

    private Date convertToDate(LocalDate localDate) {
        Instant instant = localDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
        return Date.from(instant);
    }

    /**
     * 修改订单详情
     *
     * @param sysOrder 订单详情
     * @return 结果
     */
    @Override
    public int updateSysOrder(SysOrder sysOrder)
    {
        return sysOrderMapper.updateSysOrder(sysOrder);
    }

    /**
     * 批量删除订单详情
     *
     * @param orderIds 需要删除的订单详情主键
     * @return 结果
     */
    @Override
    @Transactional // 假设你使用了Spring框架的事务管理
    public int deleteSysOrderByOrderIds(Long[] orderIds) {
        List<Long> validOrderIds = new ArrayList<>(); // 应该是List而不是Long[]
        List<Long> failedOrderIds = new ArrayList<>();

        // 预处理阶段，收集有效的订单ID和失败的订单ID
        for (Long orderId : orderIds) {
            SysUserOrderProperty sysUserOrderProperty = sysUserOrderPropertyMapper.selectSysUserOrderPropertyByOrderId(orderId);
            if (sysUserOrderProperty != null) {
                validOrderIds.add(orderId);

                // 尝试删除文件
                SysOrder sysOrder = sysOrderMapper.selectSysOrderByOrderId(orderId);
                if (sysOrder != null && sysOrder.getContract() != null) {
                    Path path = Paths.get("D:" + sysOrder.getContract());
                    try {
                        Files.deleteIfExists(path);
                    } catch (IOException e) {
                        logger.error("删除订单ID为{}的文件时发生错误", orderId, e); // 使用error级别且修正占位符使用
                        failedOrderIds.add(orderId);
                    }
                }
            } else {
                logger.error("未找到订单ID为{}的订单信息",orderId); // 修正日志打印方式
                failedOrderIds.add(orderId);
            }
        }

        // 批量删除数据库记录
        if (!validOrderIds.isEmpty()) {
            try {
                sysOrderMapper.deleteSysOrderByOrderIds(validOrderIds.toArray(new Long[0])); // 转换为数组传递给方法
                sysUserOrderPropertyMapper.deleteSysUserOrderPropertyByOrderIds(validOrderIds.toArray(new Long[0]));
            } catch (Exception e) {
                logger.error("批量删除数据库记录时发生异常", e); // 使用error级别且修正占位符使用
                // 可能需要回滚事务或进一步处理异常，但@Transactional应该会自动回滚
            }
        }
        // 返回失败的订单数量，可根据业务需求调整返回值
        return failedOrderIds.size();
    }




    /**
     * 删除订单详情信息
     *
     * @param orderId 订单详情主键
     * @return 结果
     */
    @Override
    public int deleteSysOrderByOrderId(Long orderId)
    {
        //修改房源状态为未租
        SysUserOrderProperty sysUserOrderProperty = sysUserOrderPropertyMapper.selectSysUserOrderPropertyByOrderId(orderId);
        sysPropertyMapper.updateSysPropertyStatus(0);
        //删除D盘下存储文件路径
        SysOrder sysOrder = sysOrderMapper.selectSysOrderByOrderId(sysUserOrderProperty.getOrderId());
        Path path = Paths.get("D:"+sysOrder.getContract());
        try {
            Files.deleteIfExists(path);
        } catch (IOException e) {
            logger.info("删除文件失败");
        }
        //删除订单表相关信息
        sysOrderMapper.deleteSysOrderByOrderId(sysUserOrderProperty.getOrderId());
        //删除订单关联表信息
        return sysUserOrderPropertyMapper.deleteSysUserOrderPropertyByOrderId(sysUserOrderProperty.getOrderId());
    }
}
